using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace WindowsFormsDataBaice
{
    public class ChargeForm : Form
    {
        private Panel headerPanel;
        private Panel leftPanel;
        private Panel rightPanel;
        private Panel bottomPanel;
        
        // 当前用户信息
        private int currentUserId;
        private string currentUserName;
        
        // 查询区域
        private Label lblCardNoTitle;
        private TextBox txtCardNo;
        private Button btnSearch;
        private Button btnScanCard;
        
        // 患者信息区域
        private Panel pnlPatientInfo;
        private Label lblPatientName;
        private Label lblCardBalance;
        private Label lblCardStatus;
        
        // 收费项目列表
        private Label lblChargeItemsTitle;
        private DataGridView dgvPrescriptions;
        private DataGridView dgvLabOrders;
        private Label lblTotalAmount;
        
        // 支付区域
        private Panel pnlPayment;
        private TextBox txtTotalAmount;
        private TextBox txtDiscount;
        private TextBox txtCardPayAmount;
        private TextBox txtOtherPayAmount;
        private TextBox txtRealAmount;
        private ComboBox cmbPayChannel;
        private Button btnCharge;
        private Button btnRecharge;
        
        // 数据存储
        private ChargeItemsInfo currentChargeItems;

        public ChargeForm(int userId, string userName)
        {
            this.currentUserId = userId;
            this.currentUserName = userName;
            InitializeComponent();
            SetupEventHandlers();
        }

        private void InitializeComponent()
        {
            // 设置窗体基本属性
            this.Size = new Size(1200, 800);
            this.Text = "门诊收费";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = UIStyleManager.BackgroundColor;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 创建头部面板
            headerPanel = new Panel
            {
                Size = new Size(1200, 80),
                BackColor = UIStyleManager.PrimaryColor,
                Dock = DockStyle.Top
            };

            Label lblTitleIcon = new Label
            {
                Text = IconManager.Icons.Save,
                Font = new Font("Segoe UI Emoji", 24),
                ForeColor = Color.White,
                Location = new Point(30, 20),
                AutoSize = true
            };

            Label titleLabel = new Label
            {
                Text = "门诊收费窗口",
                Font = UIStyleManager.TitleFont,
                ForeColor = Color.White,
                Location = new Point(80, 25),
                AutoSize = true
            };

            headerPanel.Controls.Add(lblTitleIcon);
            headerPanel.Controls.Add(titleLabel);

            // 创建左侧面板（查询和患者信息）
            leftPanel = new Panel
            {
                Size = new Size(400, 640),
                Location = new Point(20, 90),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
            };

            CreateSearchArea();
            CreatePatientInfoArea();
            CreatePaymentArea();

            // 创建右侧面板（收费项目列表）
            rightPanel = new Panel
            {
                Size = new Size(750, 640),
                Location = new Point(430, 90),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            CreateChargeItemsArea();

            // 创建底部按钮面板
            bottomPanel = new Panel
            {
                Size = new Size(1200, 70),
                BackColor = Color.FromArgb(240, 240, 240),
                Dock = DockStyle.Bottom
            };

            CreateBottomButtons();

            // 添加面板到窗体
            this.Controls.Add(headerPanel);
            this.Controls.Add(bottomPanel);
            this.Controls.Add(leftPanel);
            this.Controls.Add(rightPanel);
        }

        private void CreateSearchArea()
        {
            // 卡号查询标题
            lblCardNoTitle = new Label
            {
                Text = "就诊卡查询",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 20),
                Size = new Size(120, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 卡号输入框
            Label lblCardNo = new Label
            {
                Text = "就诊卡号:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(20, 60),
                Size = new Size(70, 20)
            };

            txtCardNo = new TextBox
            {
                Location = new Point(90, 55),
                Size = new Size(200, 25),
                Font = UIStyleManager.BodyFont
            };

            // 查询按钮
            btnSearch = new Button
            {
                Text = "查询",
                Location = new Point(300, 55),
                Size = new Size(60, 25),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = UIStyleManager.BodyFont
            };
            btnSearch.FlatAppearance.BorderSize = 0;

            // 扫码按钮
            btnScanCard = new Button
            {
                Text = "扫码",
                Location = new Point(300, 90),
                Size = new Size(60, 25),
                BackColor = Color.FromArgb(46, 204, 113),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = UIStyleManager.BodyFont
            };
            btnScanCard.FlatAppearance.BorderSize = 0;

            leftPanel.Controls.AddRange(new Control[] {
                lblCardNoTitle, lblCardNo, txtCardNo, btnSearch, btnScanCard
            });
        }

        private void CreatePatientInfoArea()
        {
            // 患者信息面板
            pnlPatientInfo = new Panel
            {
                Location = new Point(20, 130),
                Size = new Size(350, 120),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.FromArgb(248, 249, 250)
            };

            Label lblPatientInfoTitle = new Label
            {
                Text = "患者信息",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(15, 10),
                Size = new Size(80, 20),
                ForeColor = UIStyleManager.PrimaryColor
            };

            lblPatientName = new Label
            {
                Text = "患者姓名: 请先查询",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 40),
                Size = new Size(320, 20),
                ForeColor = Color.Gray
            };

            lblCardBalance = new Label
            {
                Text = "卡余额: ¥0.00",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 65),
                Size = new Size(320, 20),
                ForeColor = Color.Gray
            };

            lblCardStatus = new Label
            {
                Text = "卡状态: 未知",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 90),
                Size = new Size(320, 20),
                ForeColor = Color.Gray
            };

            pnlPatientInfo.Controls.AddRange(new Control[] {
                lblPatientInfoTitle, lblPatientName, lblCardBalance, lblCardStatus
            });

            leftPanel.Controls.Add(pnlPatientInfo);
        }

        private void CreatePaymentArea()
        {
            // 支付信息面板
            pnlPayment = new Panel
            {
                Location = new Point(20, 270),
                Size = new Size(350, 350),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.FromArgb(248, 249, 250)
            };

            Label lblPaymentTitle = new Label
            {
                Text = "支付信息",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(15, 10),
                Size = new Size(80, 20),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 应收金额
            Label lblTotal = new Label
            {
                Text = "应收金额:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 45),
                Size = new Size(70, 20)
            };

            txtTotalAmount = new TextBox
            {
                Location = new Point(90, 40),
                Size = new Size(100, 25),
                Font = UIStyleManager.BodyFont,
                ReadOnly = true,
                BackColor = Color.LightGray
            };

            // 优惠金额
            Label lblDiscount = new Label
            {
                Text = "优惠金额:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 80),
                Size = new Size(70, 20)
            };

            txtDiscount = new TextBox
            {
                Location = new Point(90, 75),
                Size = new Size(100, 25),
                Font = UIStyleManager.BodyFont,
                Text = "0.00"
            };

            // 医疗卡支付
            Label lblCardPay = new Label
            {
                Text = "医疗卡支付:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 115),
                Size = new Size(70, 20)
            };

            txtCardPayAmount = new TextBox
            {
                Location = new Point(90, 110),
                Size = new Size(100, 25),
                Font = UIStyleManager.BodyFont,
                Text = "0.00"
            };

            // 其他支付
            Label lblOtherPay = new Label
            {
                Text = "其他支付:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 150),
                Size = new Size(70, 20)
            };

            txtOtherPayAmount = new TextBox
            {
                Location = new Point(90, 145),
                Size = new Size(100, 25),
                Font = UIStyleManager.BodyFont,
                Text = "0.00"
            };

            // 实收金额
            Label lblReal = new Label
            {
                Text = "实收金额:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 185),
                Size = new Size(70, 20)
            };

            txtRealAmount = new TextBox
            {
                Location = new Point(90, 180),
                Size = new Size(100, 25),
                Font = UIStyleManager.BodyFont,
                ReadOnly = true,
                BackColor = Color.LightYellow
            };

            // 支付方式
            Label lblPayChannel = new Label
            {
                Text = "支付方式:",
                Font = new Font("微软雅黑", 10),
                Location = new Point(15, 220),
                Size = new Size(70, 20)
            };

            cmbPayChannel = new ComboBox
            {
                Location = new Point(90, 215),
                Size = new Size(150, 25),
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = UIStyleManager.BodyFont
            };
            cmbPayChannel.Items.AddRange(new string[] { "现金", "银行卡", "支付宝", "微信", "混合支付" });
            cmbPayChannel.SelectedIndex = 0;

            // 收费按钮
            btnCharge = IconManager.CreateSmallIconButton("确认收费", IconManager.Icons.Save, 120, 35, ButtonStyle.Success);
            btnCharge.Location = new Point(15, 260);
            btnCharge.Enabled = false;

            // 充值按钮
            btnRecharge = IconManager.CreateSmallIconButton("医疗卡充值", IconManager.Icons.Plus, 120, 35, ButtonStyle.Primary);
            btnRecharge.Location = new Point(150, 260);

            pnlPayment.Controls.AddRange(new Control[] {
                lblPaymentTitle, lblTotal, txtTotalAmount, lblDiscount, txtDiscount,
                lblCardPay, txtCardPayAmount, lblOtherPay, txtOtherPayAmount,
                lblReal, txtRealAmount, lblPayChannel, cmbPayChannel,
                btnCharge, btnRecharge
            });

            leftPanel.Controls.Add(pnlPayment);
        }

        private void CreateChargeItemsArea()
        {
            // 收费项目标题
            lblChargeItemsTitle = new Label
            {
                Text = "待收费项目",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 20),
                Size = new Size(120, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 处方列表
            Label lblPrescriptions = new Label
            {
                Text = "处方列表",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(20, 60),
                Size = new Size(80, 25),
                ForeColor = UIStyleManager.PrimaryColor
            };

            dgvPrescriptions = new DataGridView
            {
                Location = new Point(20, 90),
                Size = new Size(700, 200),
                AutoGenerateColumns = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                Font = UIStyleManager.BodyFont,
                Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
            };

            // 添加处方列表的列
            dgvPrescriptions.Columns.Add("prescriptionNo", "处方号");
            dgvPrescriptions.Columns.Add("type", "类型");
            dgvPrescriptions.Columns.Add("createTime", "开立时间");
            dgvPrescriptions.Columns.Add("amount", "金额");
            dgvPrescriptions.Columns["prescriptionNo"].Width = 120;
            dgvPrescriptions.Columns["type"].Width = 100;
            dgvPrescriptions.Columns["createTime"].Width = 150;
            dgvPrescriptions.Columns["amount"].Width = 80;

            // 检验单列表
            Label lblLabOrders = new Label
            {
                Text = "检验单列表",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(20, 310),
                Size = new Size(100, 25),
                ForeColor = UIStyleManager.PrimaryColor
            };

            dgvLabOrders = new DataGridView
            {
                Location = new Point(20, 340),
                Size = new Size(700, 200),
                AutoGenerateColumns = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                Font = UIStyleManager.BodyFont,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            // 添加检验单列表的列
            dgvLabOrders.Columns.Add("orderNo", "检验单号");
            dgvLabOrders.Columns.Add("itemName", "检验项目");
            dgvLabOrders.Columns.Add("createTime", "开立时间");
            dgvLabOrders.Columns.Add("price", "费用");
            dgvLabOrders.Columns["orderNo"].Width = 120;
            dgvLabOrders.Columns["itemName"].Width = 200;
            dgvLabOrders.Columns["createTime"].Width = 150;
            dgvLabOrders.Columns["price"].Width = 80;

            // 总金额显示
            lblTotalAmount = new Label
            {
                Text = "应收总额: ¥0.00",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(550, 550),
                Size = new Size(150, 30),
                ForeColor = Color.Red,
                TextAlign = ContentAlignment.MiddleRight,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };

            rightPanel.Controls.AddRange(new Control[] {
                lblChargeItemsTitle, lblPrescriptions, dgvPrescriptions,
                lblLabOrders, dgvLabOrders, lblTotalAmount
            });
        }

        private void CreateBottomButtons()
        {
            // 刷新按钮
            Button btnRefresh = IconManager.CreateSmallIconButton("刷新", IconManager.Icons.Refresh, 100, 45, ButtonStyle.Primary);
            btnRefresh.Location = new Point(400, 15);
            btnRefresh.Click += BtnRefresh_Click;

            // 关闭按钮
            Button btnClose = IconManager.CreateSmallIconButton("关闭", IconManager.Icons.Close, 100, 45, ButtonStyle.Danger);
            btnClose.Location = new Point(520, 15);
            btnClose.Click += BtnClose_Click;

            bottomPanel.Controls.Add(btnRefresh);
            bottomPanel.Controls.Add(btnClose);
        }

        private void SetupEventHandlers()
        {
            btnSearch.Click += BtnSearch_Click;
            btnScanCard.Click += BtnScanCard_Click;
            btnCharge.Click += BtnCharge_Click;
            btnRecharge.Click += BtnRecharge_Click;
            txtDiscount.TextChanged += PaymentAmount_TextChanged;
            txtCardPayAmount.TextChanged += PaymentAmount_TextChanged;
            txtOtherPayAmount.TextChanged += PaymentAmount_TextChanged;
        }

        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCardNo.Text.Trim()))
            {
                MessageBox.Show("请输入就诊卡号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            await LoadChargeItems(txtCardNo.Text.Trim());
        }

        private void BtnScanCard_Click(object sender, EventArgs e)
        {
            // 模拟扫码功能
            MessageBox.Show("扫码功能开发中...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private async Task LoadChargeItems(string cardNo)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    string url = $"http://101.201.170.32:5166/api/DoctorWorkstation/pending-charge-items?cardNo={cardNo}";
                    var response = await client.GetAsync(url);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"查询待收费项目: {url}");
                    System.Diagnostics.Debug.WriteLine($"响应: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                        if (apiResponse?.code == 200 && apiResponse?.data != null)
                        {
                            currentChargeItems = JsonConvert.DeserializeObject<ChargeItemsInfo>(apiResponse.data.ToString());
                            UpdateChargeItemsDisplay();
                        }
                        else
                        {
                            MessageBox.Show("未找到该卡号的待收费项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            ClearChargeItemsDisplay();
                        }
                    }
                    else
                    {
                        MessageBox.Show($"查询失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateChargeItemsDisplay()
        {
            if (currentChargeItems?.patient != null)
            {
                // 更新患者信息
                lblPatientName.Text = $"患者姓名: {currentChargeItems.patient.patientName}";
                lblCardBalance.Text = $"卡余额: ¥{currentChargeItems.patient.cardBalance:F2}";
                lblCardStatus.Text = $"卡状态: {currentChargeItems.patient.cardStatus}";
                lblPatientName.ForeColor = Color.Black;
                lblCardBalance.ForeColor = Color.Black;
                lblCardStatus.ForeColor = Color.Black;
                
                // 更新处方列表
                dgvPrescriptions.Rows.Clear();
                if (currentChargeItems.prescriptions != null)
                {
                    foreach (var prescription in currentChargeItems.prescriptions)
                    {
                        var row = dgvPrescriptions.Rows.Add();
                        dgvPrescriptions.Rows[row].Cells["prescriptionNo"].Value = prescription.prescriptionNo;
                        dgvPrescriptions.Rows[row].Cells["type"].Value = prescription.type;
                        dgvPrescriptions.Rows[row].Cells["createTime"].Value = prescription.createTime.ToString("yyyy-MM-dd HH:mm");
                        dgvPrescriptions.Rows[row].Cells["amount"].Value = $"¥{prescription.amount:F2}";
                        dgvPrescriptions.Rows[row].Tag = prescription;
                    }
                }

                // 更新检验单列表
                dgvLabOrders.Rows.Clear();
                if (currentChargeItems.laborders != null)
                {
                    foreach (var laborder in currentChargeItems.laborders)
                    {
                        var row = dgvLabOrders.Rows.Add();
                        dgvLabOrders.Rows[row].Cells["orderNo"].Value = laborder.orderNo;
                        dgvLabOrders.Rows[row].Cells["itemName"].Value = laborder.itemName;
                        dgvLabOrders.Rows[row].Cells["createTime"].Value = laborder.createTime.ToString("yyyy-MM-dd HH:mm");
                        dgvLabOrders.Rows[row].Cells["price"].Value = $"¥{laborder.price:F2}";
                        dgvLabOrders.Rows[row].Tag = laborder;
                    }
                }

                // 更新总金额
                lblTotalAmount.Text = $"应收总额: ¥{currentChargeItems.totalAmount:F2}";
                txtTotalAmount.Text = currentChargeItems.totalAmount.ToString("F2");
                
                // 默认设置医疗卡支付金额
                decimal maxCardPay = Math.Min(currentChargeItems.totalAmount, currentChargeItems.patient.cardBalance);
                txtCardPayAmount.Text = maxCardPay.ToString("F2");
                txtOtherPayAmount.Text = Math.Max(0, currentChargeItems.totalAmount - maxCardPay).ToString("F2");
                
                UpdateRealAmount();
                btnCharge.Enabled = true;
            }
        }

        private void ClearChargeItemsDisplay()
        {
            lblPatientName.Text = "患者姓名: 请先查询";
            lblCardBalance.Text = "卡余额: ¥0.00";
            lblCardStatus.Text = "卡状态: 未知";
            lblPatientName.ForeColor = Color.Gray;
            lblCardBalance.ForeColor = Color.Gray;
            lblCardStatus.ForeColor = Color.Gray;
            
            dgvPrescriptions.Rows.Clear();
            dgvLabOrders.Rows.Clear();
            lblTotalAmount.Text = "应收总额: ¥0.00";
            txtTotalAmount.Text = "0.00";
            txtDiscount.Text = "0.00";
            txtCardPayAmount.Text = "0.00";
            txtOtherPayAmount.Text = "0.00";
            txtRealAmount.Text = "0.00";
            
            btnCharge.Enabled = false;
            currentChargeItems = null;
        }

        private void PaymentAmount_TextChanged(object sender, EventArgs e)
        {
            UpdateRealAmount();
        }

        private void UpdateRealAmount()
        {
            try
            {
                decimal total = decimal.Parse(txtTotalAmount.Text);
                decimal discount = decimal.Parse(txtDiscount.Text);
                decimal cardPay = decimal.Parse(txtCardPayAmount.Text);
                decimal otherPay = decimal.Parse(txtOtherPayAmount.Text);
                
                decimal realAmount = cardPay + otherPay;
                txtRealAmount.Text = realAmount.ToString("F2");
                
                // 检查支付金额是否足够
                decimal shouldPay = total - discount;
                if (realAmount >= shouldPay)
                {
                    txtRealAmount.BackColor = Color.LightGreen;
                }
                else
                {
                    txtRealAmount.BackColor = Color.LightCoral;
                }
            }
            catch
            {
                txtRealAmount.Text = "0.00";
                txtRealAmount.BackColor = Color.LightYellow;
            }
        }

        private async void BtnCharge_Click(object sender, EventArgs e)
        {
            if (currentChargeItems == null)
            {
                MessageBox.Show("请先查询待收费项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                decimal total = decimal.Parse(txtTotalAmount.Text);
                decimal discount = decimal.Parse(txtDiscount.Text);
                decimal cardPay = decimal.Parse(txtCardPayAmount.Text);
                decimal otherPay = decimal.Parse(txtOtherPayAmount.Text);
                decimal realAmount = cardPay + otherPay;
                decimal shouldPay = total - discount;

                if (realAmount < shouldPay)
                {
                    MessageBox.Show("支付金额不足", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (cardPay > currentChargeItems.patient.cardBalance)
                {
                    MessageBox.Show("医疗卡余额不足", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var confirmMessage = $"确认收费信息：\n\n" +
                                   $"患者：{currentChargeItems.patient.patientName}\n" +
                                   $"应收金额：¥{total:F2}\n" +
                                   $"优惠金额：¥{discount:F2}\n" +
                                   $"医疗卡支付：¥{cardPay:F2}\n" +
                                   $"其他支付：¥{otherPay:F2}\n" +
                                   $"实收金额：¥{realAmount:F2}\n\n" +
                                   $"是否确认收费？";

                if (MessageBox.Show(confirmMessage, "确认收费", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    await ProcessCharge();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"支付金额格式错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task ProcessCharge()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    var prescriptionIds = new List<int>();
                    if (currentChargeItems.prescriptions != null)
                    {
                        foreach (var prescription in currentChargeItems.prescriptions)
                        {
                            prescriptionIds.Add(prescription.prescriptionId);
                        }
                    }

                    var laborderIds = new List<int>();
                    if (currentChargeItems.laborders != null)
                    {
                        foreach (var laborder in currentChargeItems.laborders)
                        {
                            laborderIds.Add(laborder.laborderId);
                        }
                    }

                    var chargeData = new
                    {
                        cardNo = currentChargeItems.patient.cardNo,
                        totalAmount = decimal.Parse(txtTotalAmount.Text),
                        discount = decimal.Parse(txtDiscount.Text),
                        realAmount = decimal.Parse(txtRealAmount.Text),
                        payChannel = cmbPayChannel.Text,
                        cashierId = currentUserId,
                        cardPayAmount = decimal.Parse(txtCardPayAmount.Text),
                        otherPayAmount = decimal.Parse(txtOtherPayAmount.Text),
                        prescriptionIds = prescriptionIds,
                        laborderIds = laborderIds
                    };

                    var json = JsonConvert.SerializeObject(chargeData, Formatting.Indented);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    string url = "http://101.201.170.32:5166/api/DoctorWorkstation/process-charge";
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"收费请求: {json}");
                    System.Diagnostics.Debug.WriteLine($"响应: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                        if (apiResponse?.code == 200)
                        {
                            string successMessage = "收费成功！";
                            // 安全地检查data是否包含chargeId
                            try
                            {
                                if (apiResponse?.data != null && apiResponse.data is Newtonsoft.Json.Linq.JObject)
                                {
                                    var dataObj = apiResponse.data as Newtonsoft.Json.Linq.JObject;
                                    if (dataObj != null && dataObj["chargeId"] != null)
                                    {
                                        successMessage += $"\n收费单号: {dataObj["chargeId"]}";
                                    }
                                }
                            }
                            catch
                            {
                                // 忽略chargeId解析错误，继续显示成功消息
                            }
                            
                            MessageBox.Show(successMessage, "收费成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            ClearChargeItemsDisplay();
                            txtCardNo.Text = "";
                        }
                        else
                        {
                            string errorMessage = apiResponse?.msg?.ToString() ?? "收费失败";
                            MessageBox.Show(errorMessage, "收费失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"收费失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnRecharge_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCardNo.Text.Trim()))
            {
                MessageBox.Show("请先输入就诊卡号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 打开充值窗口
            RechargeForm rechargeForm = new RechargeForm(txtCardNo.Text.Trim(), currentUserId, currentUserName);
            if (rechargeForm.ShowDialog() == DialogResult.OK)
            {
                // 充值成功后重新查询
                LoadChargeItems(txtCardNo.Text.Trim());
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtCardNo.Text.Trim()))
            {
                LoadChargeItems(txtCardNo.Text.Trim());
            }
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

    // 数据模型类
    public class ChargeItemsInfo
    {
        public PatientChargeInfo patient { get; set; }
        public List<PrescriptionChargeInfo> prescriptions { get; set; }
        public List<LabOrderChargeInfo> laborders { get; set; }
        public decimal totalAmount { get; set; }
    }

    public class PatientChargeInfo
    {
        public int patientId { get; set; }
        public string patientName { get; set; }
        public string cardNo { get; set; }
        public decimal cardBalance { get; set; }
        public string cardStatus { get; set; }
    }

    public class PrescriptionChargeInfo
    {
        public int prescriptionId { get; set; }
        public string prescriptionNo { get; set; }
        public string type { get; set; }
        public DateTime createTime { get; set; }
        public decimal amount { get; set; }
    }

    public class LabOrderChargeInfo
    {
        public int laborderId { get; set; }
        public string orderNo { get; set; }
        public string itemName { get; set; }
        public DateTime createTime { get; set; }
        public decimal price { get; set; }
    }
} 